package cn.com.bluemoon.daps.model.utils.factory.impl.key;

import cn.com.bluemoon.daps.model.dto.SubordinateKeyDto;
import cn.com.bluemoon.daps.model.entity.DapDataModelSubordinateKey;
import cn.com.bluemoon.daps.model.entity.DapDataModelTableField;
import cn.com.bluemoon.daps.model.utils.contrast.Constant;
import cn.com.bluemoon.daps.model.utils.factory.KeyScriptFactory;
import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author karry
 * @Data 2021/9/7
 * @Time:9:28
 */
public class PostgreKeyScript extends AbsKeyScript {

    @Override
    public String createKeyScript(List<SubordinateKeyDto> keys) {
        return createKeyPublicCode(keys, "");
    }

    @Override
    public void addKeyScript(List<DapDataModelSubordinateKey> keyList, List<DapDataModelTableField> fields,
                               String tableSchema, String tableName, Map<String, String> map) {

        String schema = StringUtils.isNotBlank(tableSchema) ? tableSchema + "." : "";
        List<String> keyScript = Lists.newArrayList();
        for (DapDataModelSubordinateKey key : keyList) {
            List<String> ids = Arrays.asList(key.getFieldIds().split(","));
            String fieldName = fields.stream().filter(f -> ids.contains(f.getId())).map(DapDataModelTableField::getFieldName)
                    .collect(Collectors.joining(",", "(", ")"));
            String keyType = key.getKeyType() == 2 ? "" : "unique";
            String singleScript = String.format("CREATE %s index %s on %s%s %s;", keyType, key.getKeyName(), schema, tableName, fieldName);
            keyScript.add(singleScript);
        }
        String collect = keyScript.stream().collect(Collectors.joining());
        map.put(Constant.CK, collect);
    }

    @Override
    public String modifyKeyScript() {
        return null;
    }

    @Override
    public void deleteKeyScript(List<DapDataModelSubordinateKey> keyList, String tableName, Map<String, String> map) {

        List<String> keyScript = keyList.stream().map(key -> String.format("drop index %s;", key.getKeyName())).collect(Collectors.toList());
        String collect = keyScript.stream().collect(Collectors.joining());
        map.put(Constant.DK, collect);
    }
}
